<template>
  <div class="app-container" v-loading="pageLoading">
    <el-button class="fr" type="primary" plain @click="createVisible = true">创建</el-button>
    <div class="filter-container">
      <el-input style="width: 240px;" placeholder="输入任务号/容器号查询" clearable prefix-icon="el-icon-search"
        class="filter-item" v-model="query.queryString" @change="research"></el-input>
      <el-button class="filter-item" type="success" plain @click="research">查询</el-button>
    </div>
    <z-table ref="ztable" :list="list" :tableProps="tableProps" :columns="columns">
      <template v-slot:content="v">
        <template v-if="v.key === 'TaskCode'">
          <a href="#" :class="{ pointer: v.row.TaskDetailId, 'text-primary': v.row.TaskDetailId }"
            @click.prevent="seeTaskDetail(v.row)">{{ v.row[v.key] }}</a>
        </template>
        <span v-else-if="v.key === 'StatusTxt'">
          <el-tag :type="v.row.StatusTagType">{{ v.row[v.key] }}</el-tag>
        </span>
        <span v-else-if="v.key === 'TypeTxt'">
          <el-tag class="text-label" :class="v.row.TypeClass">{{ v.row[v.key] }}</el-tag>
        </span>
        <span v-else-if="v.key === 'PriorityTxt'">
          <el-tag v-if="!!v.row[v.key]" :type="v.row.PriorityTagType">{{ v.row[v.key] }}</el-tag>
        </span>
        <span v-else>{{ v.row[v.key] }}</span>
      </template>
      <template v-slot:operation="v">
        <template v-if="v.row.TaskDetailId == v.row.TaskId">
          <a href="#" class="text-warning" :data-disabled="checkBtnIsOnclick(v.row.Status, true)"
            :data-loading="SuspendMainTaskLoading && opeartionIndex == v.$index"
            @click.prevent="doMainTask(v.row, 'SuspendMainTask', v.$index)">强制暂停</a>
          <a href="#" class="text-success" :data-disabled="checkBtnIsOnclick(v.row.Status, false)"
            :data-loading="opeartionIndex && opeartionIndex == v.$index"
            @click.prevent="doMainTask(v.row, 'ForceFinishMainTask', v.$index)">强制完成</a>
          <a href="#" class="text-danger" :data-disabled="checkBtnIsOnclick(v.row.Status, false)"
            :data-loading="CancelMainTaskLoading && opeartionIndex == v.$index"
            @click.prevent="doMainTask(v.row, 'CancelMainTask', v.$index)">取消任务</a>
        </template>
        <template v-else>
          <a href="#" class="text-warning" :data-disabled="checkBtnIsOnclick(v.row.Status, true, true)"
            :data-loading="SuspendTaskDetLoading && opeartionIndex == v.$index"
            @click.prevent="doDetailTask(v.row, 'SuspendTaskDet', v.$index)">暂停</a>
          <a href="#" class="text-primary" :data-disabled="checkBtnIsOnclick(v.row.Status, false, true)"
            :data-loading="ContExecTaskDetLoading && opeartionIndex == v.$index"
            @click.prevent="doDetailTask(v.row, 'ContExecTaskDet', v.$index)">继续</a>
          <a href="#" class="text-success" :data-disabled="checkBtnIsOnclick(v.row.Status, false, true)"
            :data-loading="ForceFinishTaskDetLoading && opeartionIndex == v.$index"
            @click.prevent="doDetailTask(v.row, 'ForceFinishTaskDet', v.$index)">完成</a>
          <a href="#" class="text-danger" :data-disabled="checkBtnIsOnclick(v.row.Status, false, true)"
            :data-loading="CancelTaskDetLoading && opeartionIndex == v.$index"
            @click.prevent="doDetailTask(v.row, 'CancelTaskDet', v.$index)">取消</a>
        </template>
      </template>
    </z-table>
    <z-pagination :pagination="pagination" :total="total" v-model:page="query.page" v-model:limit="query.size"
      @change="getList"></z-pagination>
    <z-form-dialog name="任务优先级" :data="data" :formProps="formProps" :fields="fields" @submit="submit"
      :submitLoading="submitLoading" v-model="editFormVisible"></z-form-dialog>
    <!-- 子任务明细 -->
    <driver-detail-dialog v-model="detailVisible" :query="driverDetailQuery" :isAutoRequst="true"
      :controlBtnDisabledShow="true" @statusSuccesCallBack="research"></driver-detail-dialog>
    <!-- 创建主任务 -->
    <create-task-dialog v-model="createVisible" @succesCallBack="research"></create-task-dialog>
  </div>
</template>

<script>
import commonMixin from '@/views/_common/mixin'
import driverDetailDialog from './components/driverDetailDialog.vue'
import createTaskDialog from './components/createTaskDialog.vue'
import _ from 'lodash'
export default {
  mixins: [commonMixin],
  components: { driverDetailDialog, createTaskDialog },
  name: 'wcsTask',
  data: function () {
    return {
      api: this.$api.wcsUrl + 'wcs/task/',
      name: 'WCS任务监控',
      postForList: true,
      query: {
        page: 1,
        size: 10,
        queryString: '',
      },
      columns: [
        { title: 'WCS任务编号', key: 'TaskCode', width: 160,fixed:'left' },
        { title: '任务来源', key: 'SourceTxt', width: 100, fixed: 'left' },
        { title: '任务类型', key: 'TypeTxt', width: 100, fixed: 'left' },
        { title: '任务条码', key: 'Barcode', width: 100, fixed: 'left' },
        { title: '任务状态', key: 'StatusTxt', width: 100 },
        { title: '开始位置', key: 'StartLocationUserCode', width: 150 },
        { title: '起点执行设备', key: 'StartLocationDeviceName', width: 150 },
        { title: '结束位置', key: 'EndLocationUserCode', width: 150 },
        { title: '终点执行设备', key: 'EndLocationDeviceName', width: 150 },
        { title: '当前位置', key: 'CurrentLocationUserCode', width: 150 },
        { title: '当前设备', key: 'CurrentLocationUserCode', width: 150 },
        { title: '优先级', key: 'PriorityTxt', width: 68 },
        { title: '信息', key: 'Description', width: 160 },
        { title: '来源任务码', key: 'InterCode', width: 120 },
        { title: '任务创建时间', key: 'CreateAt'},
        { title: '完成时间', key: 'FinishedAt' },
      ],
      tableProps: {
        border: true,
        opsColWith: 220,
        lazy: true,
        load: this.showTaskDetail,
        'row-key': 'TaskDetailId',
        'tree-props': { children: 'Children', hasChildren: 'HasChildren' },
      },
      typeOptions: [
        { label: '未知', value: 0, class: 'bg-gray' },
        { label: '出库', value: 1, class: 'bg-blue' },
        { label: '入库', value: 2, class: 'bg-green' },
        { label: '移库', value: 3, class: 'bg-yellow' },
        { label: 'agv入库', value: 4, class: 'bg-yellow' },
      ],
      statusOptions: [
        { label: '新任务', value: 0, tagType: 'primary' },
        { label: '已发送', value: 1, tagType: 'success' },
        { label: '正在运行', value: 2, tagType: 'success' },
        { label: '暂停', value: 3, tagType: 'warning' },
        { label: '发生错误', value: 4, tagType: 'danger' },
        { label: '被取消', value: 5, tagType: 'info' },
        { label: '已完成', value: 6, tagType: 'success' },
        { label: '强制暂停', value: 9, tagType: 'warning' },
      ],
      sourceOptions: [
        { label: '未知', value: 0 },
        { label: 'WCS', value: 1 },
        { label: 'WMS', value: 2 },
      ],
      priorityOptions: [
        { label: '暂缓', value: -1, tagType: 'info' },
        { label: '一般', value: 0, tagType: 'primary' },
        { label: '高', value: 5, tagType: 'warning' },
        { label: '特高', value: 10, tagType: 'danger' },
      ],
      lastExpandItem: null,
      craneList: [],
      fields: [
        {
          title: 'WCS任务编号',
          key: 'TaskCode',
          span: 12,
          props: {
            disabled: true,
          },
        },
        {
          title: '任务类型',
          key: 'TypeTxt',
          span: 12,
          props: {
            disabled: true,
          },
        },
        {
          title: '开始位置',
          key: 'StartLocationUserCode',
          span: 12,
          props: {
            disabled: true,
          },
        },
        {
          title: '结束位置',
          key: 'EndLocationUserCode',
          span: 12,
          props: {
            disabled: true,
          },
        },
        { title: '优先级', key: 'Priority', span: 24, name: 'select', options: [] },
      ],
      detailVisible: false,
      driverDetailQuery: '',
      //创建任务
      createVisible: false,
      // 控制按钮loading
      opeartionIndex: null,
      SuspendMainTaskLoading: false,
      CancelMainTaskLoading: false,
      ForceFinishMainTaskLoading: false,
      SuspendTaskDetLoading: false,
      ContExecTaskDetLoading: false,
      ForceFinishTaskDetLoading: false,
      CancelTaskDetLoading: false,
    }
  },
  methods: {
    // 判断任务的按钮权限是否可以执行
    checkBtnIsOnclick(status, isPuase, isChildren = false) {
      if (!isChildren) {
        // 主任务
        return (
          this.SuspendMainTaskLoading ||
          this.CancelMainTaskLoading ||
          this.ForceFinishMainTaskLoading ||
          this.SuspendTaskDetLoading ||
          this.ContExecTaskDetLoading ||
          this.ForceFinishTaskDetLoading ||
          this.CancelTaskDetLoading ||
          (status == 9 && isPuase) ||
          (![9].includes(status) && !isPuase) ||
          [4, 5, 6, 7, 8].includes(status)
        )
      } else {
        return (
          this.SuspendMainTaskLoading ||
          this.CancelMainTaskLoading ||
          this.ForceFinishMainTaskLoading ||
          this.SuspendTaskDetLoading ||
          this.ContExecTaskDetLoading ||
          this.ForceFinishTaskDetLoading ||
          this.CancelTaskDetLoading ||
          ([3, 9].includes(status) && isPuase) ||
          (![3].includes(status) && !isPuase) ||
          [4, 5, 6, 7, 8].includes(status)
        )
      }
    },
    // 查看子任务详情
    seeTaskDetail(row) {
      if (row.TaskDetailId == row.TaskId) return
      this.driverDetailQuery = row.TaskDetailId
      this.detailVisible = true
    },
    formatList(list) {
      let tmp = _.cloneDeep(list)
      return tmp.map((i) => {
        i.SourceTxt = this.sourceOptions.find((x) => x.value == i.TaskSource)?.label
        i.TypeTxt = this.typeOptions.find((x) => x.value == i.TaskType)?.label
        i.TypeClass = this.typeOptions.find((x) => x.value == i.TaskType)?.class
        i.StatusTxt = this.statusOptions.find((x) => x.value == i.Status)?.label
        i.StatusTagType = this.statusOptions.find((x) => x.value == i.Status)?.tagType
        i.PriorityTxt = this.priorityOptions.find((x) => x.value == i.Priority)?.label
        i.PriorityTagType = this.priorityOptions.find((x) => x.value == i.Priority)?.tagType
        if (!i.TaskDetailId) {
          i.HasChildren = true
          i.TaskDetailId = i.TaskId
        }
        return i
      })
    },
    showTaskDetail(item, node, resolve) {
      this.lastExpandItem = { item, node, resolve }
      this.http.get(this.api + 'GetDetailTasks', { taskCode: item.TaskCode }).then((r) => {
        resolve(this.formatList(r))
      })
    },
    handleMoreClick(type, row, index) {
      if (type == 'EditPriority') {
        this.editPriority(row)
        return
      }
      this.doMainTask(row, type, index)
    },
    doMainTask(task, type, index) {
      this.opeartionIndex = index
      this.$confirm('确认执行此操作？')
        .then((r) => {
          if (r != 'confirm') return
          this[`${type}Loading`] = true
          this.http.post(this.api + type, {
            taskcode: task.TaskCode,
          })
            .then((r) => {
              this.$message.success('操作成功')
              this.getList()
              this.refreshChildren()
            })
            .finally(() => {
              this[`${type}Loading`] = false
              this.opeartionIndex = null
            })
        })
        .catch(() => {
          this[`${type}Loading`] = false
        })
    },
    doDetailTask(task, type, index) {
      this.opeartionIndex = index
      this.$confirm('确认执行此操作？')
        .then((r) => {
          if (r != 'confirm') return
          this[`${type}Loading`] = true
          this.http.post(this.api + type, {
            taskcode: task.TaskDetailId,
          })
            .then((r) => {
              this.$message.success('操作成功')
              this.getList()
              this.refreshChildren()
            })
            .finally(() => {
              this[`${type}Loading`] = false
              this.opeartionIndex = null
            })
        })
        .catch(() => {
          this[`${type}Loading`] = false
        })
    },
    editPriority(task) {
      this.data = _.cloneDeep(task)
      this.editFormVisible = true
    },
    refreshChildren() {
      if (this.lastExpandItem) {
        let { item, node, resolve } = this.lastExpandItem
        this.showTaskDetail(item, node, resolve)
      }
    },
    getDictionary() {
      this.http.post('api/Sys_Dictionary/GetVueDictionary', [
        "WMS_TaskType",

      ]).then(r => {
        this.typeOptions = r.find(i => i.DictionaryNo =="WMS_TaskType")?.data.map(i => {
          return {
            label: i.value,
            value: i.key,
          }
        })
      })
    },
    submit() {
      this.submitLoading = true
      this.http.post(
        this.api + 'PriorityEdit',
        {
          TaskCode: this.data.TaskCode,
          Priority: this.data.Priority,
        },
        'post',
      )
        .then((r) => {
          this.$message.success('操作成功')
          this.editFormVisible = false
          this.getList()
          this.refreshChildren()
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
  },
  created: function () {
    this.getDictionary()
    this.getList()
    this.setFieldOptions('Priority', this.priorityOptions, 'value', 'label')

  },
}
</script>
<style scoped></style>
